package com.ckf.login_wx.controller;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckf.login_wx.entity.Repertory;
import com.ckf.login_wx.entity.RepertoryNum;
import com.ckf.login_wx.entity.RepertoryXH;
import com.ckf.login_wx.entity.Xinsell;
import com.ckf.login_wx.servic.RepertoryNumService;
import com.ckf.login_wx.servic.RepertoryService;
import com.ckf.login_wx.servic.RepertoryXHService;
import com.ckf.login_wx.servic.SellService;
import com.ckf.login_wx.servic.XinsellService;
import com.ckf.login_wx.util.Getpo;
import com.github.pagehelper.PageHelper;

@RestController
@RequestMapping("/Sp")
public class SpRepertorycontroller {
	@Autowired
    private RepertoryService repertoryService;
	@Autowired
    private RepertoryXHService repertoryXHService;
	@Autowired
    private RepertoryNumService repertoryNumService;
	@Autowired
    private SellService sellService;
	@Autowired
    private XinsellService XinsellService;
	@PostMapping("/addstockxh")
	public Object addstockXH(int id,String modele,String weight,String colour, double money,Integer wall,String faf){
		if(repertoryXHService.list(new QueryWrapper<RepertoryXH>().eq("modele", modele)).size()!=0&&faf.equals("add")){
			return "该型号规则已存在!";
		}
	    String stu="";
	    RepertoryXH RepertoryXH=new RepertoryXH();
	    RepertoryXH.setModele(modele);
	    RepertoryXH.setWeight(weight);
	    RepertoryXH.setColour(colour);
	    RepertoryXH.setWall(wall);
	    RepertoryXH.setMoney(money);
		if(faf.equals("add")){
	        if (repertoryXHService.save(RepertoryXH)){
	        	stu="添加成功";
	        }else {
	        	stu="添加失败";
	        }
		}
		if(faf.equals("up")){
			String modelestu=repertoryXHService.getById(id).getModele();
//			String colourstu=repertoryXHService.getById(id).getColour();
//			String weightstu=repertoryXHService.getById(id).getWeight();
//			int wallint=repertoryXHService.getById(id).getWall();
			RepertoryXH.setId(id);
			
	        if (repertoryXHService.updateById(RepertoryXH)){
	        	//规范修改后还要修改三个地方，库单剩余、货物信息、库单记录
	        	List<Xinsell> selllist=XinsellService.list(new QueryWrapper<Xinsell>().eq("modele", modelestu));
	        	for (int i = 0; i < selllist.size(); i++) {
	        		Xinsell Xinsell=selllist.get(i);
	        		Xinsell.setModele(modele);
	        		XinsellService.updateById(Xinsell);
				}
	        	List<Repertory> Repertorylist=repertoryService.list(new QueryWrapper<Repertory>().eq("modele", modelestu));
	        	for (int i = 0; i < Repertorylist.size(); i++) {
	        		Repertory Repertory=Repertorylist.get(i);
	        		Repertory.setModele(modele);
	        		Repertory.setColour(colour);
	        		Repertory.setWeight(weight);
	        		Repertory.setWall(wall);
	        		repertoryService.updateById(Repertory);
				}
	        	List<RepertoryNum> RepertoryNumlist=repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", modelestu));
	        	for (int i = 0; i < RepertoryNumlist.size(); i++) {
	        		RepertoryNum RepertoryNum=RepertoryNumlist.get(i);
	        		RepertoryNum.setModele(modele);
	        		RepertoryNum.setWall(wall);
	        		RepertoryNum.setColour(colour);
	        		RepertoryNum.setWeight(weight);
	        		repertoryNumService.updateById(RepertoryNum);
				}
	        	
	        	
	        	stu="修改成功";
	        }else {
	        	stu="修改失败";
	        }
		}
	    return stu;
	}
	@RequestMapping("/selestockxh")
    public Object selestockXH(HttpServletRequest request){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	Map<String, Object> map = new HashMap<>();
    	List<RepertoryXH> a= repertoryXHService.list();
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",repertoryXHService.list());
        return map;
    }
    @GetMapping("/delestockxhbyid")
    public Object delestockxhbyid(int id){
    	Map<String, Object> map = new HashMap<>();
        if (repertoryXHService.removeById(id)){
            map.put("result","删除成功");
        }else {
            map.put("result","删除失败");
        }
    return map;
    }
    @RequestMapping("/delestockxhall")
    public Object delestockXHall(String[] id){
    	
    	for (int i = 0; i < id.length; i++) {
    		try {
    			if(id[i].equals(""))continue;
    	    	int idint = Integer.parseInt(id[i]+"");
    	    	repertoryXHService.removeById(idint);
			} catch (Exception e) {
				System.out.println("***********************************异常*************************************");
				return "异常";
			}
		}
		return "删除成功";
    }
	@PostMapping("/addstock")
	public Object addstock(int id,String colour, int wall,String time, String weight,String saisie,String modele,int quantite,String faf) throws ParseException{
	    String stu="";
		Repertory Repertory=new Repertory();
	    Repertory.setColour(colour);
	    Repertory.setModele(modele);
	    
	    double moneyxh = repertoryXHService.list(new QueryWrapper<RepertoryXH>().eq("modele", modele)).get(0).getMoney();
	    
	    Repertory.setQuantite(quantite);
	    Repertory.setNum(quantite);
	    Repertory.setSaisie(saisie);
	    Repertory.setWall(wall);
	    Repertory.setWeight(weight);
	    Repertory.setSaisie(saisie);
	    Repertory.setMoney(moneyxh*quantite);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Repertory.setTime(simpleDateFormat.parse(time));
		if(faf.equals("add")){
			if (repertoryService.save(Repertory)){
				if(repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", modele)).size()==0){
					RepertoryNum RepertoryNum=new RepertoryNum();
					RepertoryNum.entity(Repertory);
					repertoryNumService.save(RepertoryNum);
				}else{
					RepertoryNum RepertoryNum=repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", modele)).get(0);
					RepertoryNum.setQuantite(RepertoryNum.getQuantite()+quantite);
					RepertoryNum.setNum(RepertoryNum.getNum()+quantite);
					repertoryNumService.updateById(RepertoryNum);
				}
	        	stu="添加成功";
	        }else {
	        	stu="添加失败";
	        }     
		}
		if(faf.equals("up")){
			Repertory.setId(id);
	        if (repertoryService.updateById(Repertory)){
	        	stu="修改成功";
	        }else {
	        	stu="修改失败";
	        }
		}
	    return stu;
	}

	@RequestMapping("/selestock")
    public Object selestock(HttpServletRequest request){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	Map<String, Object> map = new HashMap<>();

    	HttpSession session= request.getSession();
        String username = session.getAttribute("username")+"";
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
        if(quxian.equals("0")){
    		System.out.println("进入角色："+truename);
    		List<Repertory> a= repertoryService.list(new QueryWrapper<Repertory>().eq("saisie",truename).orderByDesc("time"));
        	map.put("code",0);
            map.put("count",a.size());
            map.put("msg"," ");
        	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
            map.put("data",repertoryService.list(new QueryWrapper<Repertory>().eq("saisie",truename).orderByDesc("time")));
            return map;
    	}
    	
    	
    	List<Repertory> a= repertoryService.list(new QueryWrapper<Repertory>().orderByDesc("time"));
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",repertoryService.list(new QueryWrapper<Repertory>().orderByDesc("time")));
        return map;
    }
	@RequestMapping("/selestocknum")
    public Object selestocknum(HttpServletRequest request){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	Map<String, Object> map = new HashMap<>();
    	List<RepertoryNum> a= repertoryNumService.list();
    	int num=0,quantite=0;
    	for (int j = 0; j < a.size(); j++) {
			num+=a.get(j).getNum();
			quantite+=a.get(j).getQuantite();
		}
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",repertoryNumService.list());
        map.put("num",num);
        map.put("quantite",quantite);
        return map;
    }
	@RequestMapping("/selestocksearch")
    public Object selestocksearch(HttpServletRequest request,String modele,String wall,String weight,String colour,String time,String saisie){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	
    	QueryWrapper<Repertory> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("wall", wall)
        			.like("modele", modele)
        			.like("saisie", saisie)
        			.like("colour", colour)
        			.like("weight", weight);

        if(time!=null&&!time.equals("")&&time.length()>13&&time.indexOf("-")!=-1){
            String timestart=time.substring(0,10);
            String timeend=time.substring(12);
            queryWrapper.le("time", timeend);
            queryWrapper.ge("time", timestart);
        }
    	
    	Map<String, Object> map = new HashMap<>();
    	List<Repertory> a= repertoryService.list(queryWrapper);
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",repertoryService.list(queryWrapper));
        return map;
    }
	@RequestMapping("/selestocknumsearch")
    public Object selestockNUMsearch(HttpServletRequest request,String modele,String wall,String weight,String colour,String time){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	
    	QueryWrapper<RepertoryNum> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("wall", wall)
        			.like("modele", modele)
        			.like("colour", colour)
        			.like("weight", weight);

        if(time!=null&&!time.equals("")&&time.length()>13&&time.indexOf("-")!=-1){
            String timestart=time.substring(0,10);
            String timeend=time.substring(12);
            queryWrapper.le("time", timeend);
            queryWrapper.ge("time", timestart);
        }
    	
    	Map<String, Object> map = new HashMap<>();
    	List<RepertoryNum> a= repertoryNumService.list(queryWrapper);
    	int num=0,quantite=0;
    	for (int j = 0; j < a.size(); j++) {
			num+=a.get(j).getNum();
			quantite+=a.get(j).getQuantite();
		}
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",repertoryNumService.list(queryWrapper));
        map.put("num",num);
        map.put("quantite",quantite);
        return map;
    }
	//查询所有型号
	@RequestMapping("/seleallstockbymodele")
    public Object seleallstockbymodele(){
		Map<String, Object> map = new HashMap<>();
        List<Repertory> a= repertoryService.list();
		List<String> modele =new ArrayList<String>();
    	for (int j = 0; j < a.size(); j++) {
    		modele.add(a.get(j).getModele());
		}

        map.put("count",modele.size());
        map.put("data",modele);
        return map;
    }
    @PostMapping("/upstockbyid")
    public Object upstockbyid(String id,String modele,String weight,String colour,int wall,String time,int quantite,String saisie) throws ParseException{
    	Map<String, Object> map = new HashMap<>();
        Integer i = Integer.parseInt(id);
        Repertory Repertory=new Repertory();
        Repertory.setId(i);
        Repertory.setModele(modele);
        Repertory.setWeight(weight);
        Repertory.setColour(colour);
        Repertory.setWall(wall);
        Repertory.setQuantite(quantite);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Repertory.setTime(simpleDateFormat.parse(time));
        Repertory.setSaisie(saisie);
		if (repertoryService.updateById(Repertory)){
            map.put("code",200);
            map.put("result","修改成功");
            System.out.println("修改成功");
        }else {
        	map.put("code",200);
            map.put("result","no");
        }
        return map;
    }
    @GetMapping("/selestockbyid")
    public Object selestockbyid(String id){
    	Integer idint = Integer.parseInt(id);
        return repertoryService.getById(idint);
    }
    @RequestMapping("/selestockxhbyid")
    public Object selestockXHbyid(String id){
    	Integer idint = Integer.parseInt(id);
        return repertoryXHService.getById(idint);
    }
    @RequestMapping("/selestockquantite")
    public boolean selestockquantite(String modele,int quantite){
    	if(modele.equals("运费"))return true;
    	List<RepertoryNum> a=repertoryNumService.list((QueryWrapper<RepertoryNum>)Getpo.one("modele", modele));
    	int sum=a.get(0).getNum();
    	/*for (int i = 0; i < a.size(); i++) {
			sum+=a.get(i).getNum();
		}*/
    	if(sum>quantite||sum==quantite)return true;
        return false;
    }
    @RequestMapping("/delestockall")
    public Object delestockall(String[] id){
    	
    	for (int i = 0; i < id.length; i++) {
    		try {
    			if(id[i].equals(""))continue;
    	    	int idint = Integer.parseInt(id[i]+"");
        		repertoryService.removeById(idint);
			} catch (Exception e) {
				System.out.println("***********************************异常*************************************");
				return "异常";
			}
		}
		return "删除成功";
    }
    @GetMapping("/delestockbyid")
    public Object delestockbyid(int id){
    	Map<String, Object> map = new HashMap<>();
    	Repertory Repertory= repertoryService.getById(id);
        if (repertoryService.removeById(id)){
			if(repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", Repertory.getModele())).get(0).getQuantite()==Repertory.getQuantite()){
				repertoryNumService.remove(new QueryWrapper<RepertoryNum>().eq("modele", Repertory.getModele()));
			}else{
				RepertoryNum RepertoryNum=repertoryNumService.list(new QueryWrapper<RepertoryNum>().eq("modele", Repertory.getModele())).get(0);
				RepertoryNum.setQuantite(RepertoryNum.getQuantite()-Repertory.getQuantite());
				RepertoryNum.setNum(RepertoryNum.getNum()-Repertory.getQuantite());
				repertoryNumService.updateById(RepertoryNum);
			}
            map.put("result","删除成功");
        }else {
            map.put("result","删除失败");
        }
    return map;
    }
    @RequestMapping("/stocktotalInfo")
    public Object stocktotalInfo(HttpServletRequest request,String colour, String wall,String time, String weight,String saisie,String modele){
    	QueryWrapper<Repertory> queryWrapper = new QueryWrapper<>();

        queryWrapper.like("colour", colour)
		.like("wall", wall)
		.like("weight", weight)
		.like("saisie", saisie)
		.like("modele", modele);
        if(time!=null&&!time.equals("")&&time.length()>13&&time.indexOf("-")!=-1){
            String timestart=time.substring(0,10);
            String timeend=time.substring(12);
            queryWrapper.le("time", timeend);
            queryWrapper.ge("time", timestart);
        }

    	HttpSession session= request.getSession();
        String username = session.getAttribute("username")+"";
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
    	//制单员和销售只能看自己的
        System.out.println("******************************"+quxian);
    	if(quxian.equals("0")){
    		System.out.println("进入角色："+truename);
            queryWrapper.eq("saisie",truename);
    	}
        
    	double total=0;int num=0,quantite=0;
    	List<Repertory> a=repertoryService.list(queryWrapper);
    	for (int i = 0; i < a.size(); i++) {
			//total+=mate.get(i).getMoney();
			num+=a.get(i).getNum();
			quantite+=a.get(i).getQuantite();
			
		}
        Map<String, Object> map = new HashMap<>();
       // map.put("total",total);
        map.put("num",num);  
        map.put("quantite",quantite);  
        return map;
    }
    @RequestMapping("/stocktotal")
    public Object stocktotal(HttpServletRequest request){
    	double total=0;int num=0,quantite=0;
    	HttpSession session= request.getSession();
        String username = session.getAttribute("username")+"";
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
    	QueryWrapper<Repertory> queryWrapper = new QueryWrapper<>();
    	//制单员和销售只能看自己的

    	List<Repertory> a=repertoryService.list();
    	
        System.out.println("******************************"+quxian);
    	if(quxian.equals("0")){
    		System.out.println("进入角色："+truename);
            queryWrapper.eq("saisie",truename);
            a=repertoryService.list(queryWrapper);
    	}
    	
    	
    	for (int i = 0; i < a.size(); i++) {
			//total+=mate.get(i).getMoney();
			num+=a.get(i).getNum();
			quantite+=a.get(i).getQuantite();
		}

        
    	
    	
        Map<String, Object> map = new HashMap<>();
        //map.put("total",total);
        map.put("num",num);  
        map.put("quantite",quantite);  
        return map;
    }
}
